<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home/welcome' }"
        >首页</el-breadcrumb-item
      >
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <!-- Steps 步骤条 -->
      <el-steps :active="active - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 添加表单区域 -->
      <el-form
        :model="addGoodsForm"
        :rules="addGoodsRules"
        ref="addGoodsFormRef"
        label-position="top"
      >
        <!-- Tabs 标签页 -->
        <el-tabs
          tab-position="left"
          v-model="active"
          @tab-click="tabsClick"
          :before-leave="beforeLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                type="number"
                v-model="addGoodsForm.goods_price"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                type="number"
                v-model="addGoodsForm.goods_weight"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                type="number"
                v-model="addGoodsForm.goods_number"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="goodsList"
                :props="{
                  expandTrigger: 'hover',
                  label: 'cat_name',
                  value: 'cat_id'
                }"
                @change="classifyChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 动态参数 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
            >
              <!-- 参数可选项 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 静态属性 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyList"
              :key="item.attr_id"
            >
              <!-- 参数可选项 -->
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-form-item>
              <!-- 上传图片功能 -->
              <el-upload
                :action="uploadURL"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                list-type="picture"
                :headers="headersObj"
                :on-success="handleSucess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑区域 -->
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="addBtn" @click="addFormBtn"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="preview-img" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import { getGoodsApi, getParamsListApi, getAddApi } from '@/api/goods.js'
export default {
  name: 'AddGoods',
  data() {
    return {
      // 控制步骤条的指向
      active: '0',
      // 添加商品表单数据双向绑定
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        // 参数类型
        attrs: [],
        // 上传的图片临时路径（对象）
        pics: [],
        // 富文本内容
        goods_introduce: ''
      },
      // 添加商品表单效验
      addGoodsRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类列表数据
      goodsList: [],
      // 动态参数列表
      manyList: [],
      // 静态属性列表
      onlyList: '',
      // 上传图片的URL地址
      uploadURL: 'https://lianghj.top:8888/api/private/v1/upload',
      // 上传图片组件的headers请求头对象
      headersObj: {
        Authorization: window.sessionStorage.getItem('tokenUser')
      },
      // 图片预览路径
      previewPath: '',
      // 控制图片预览框的显示隐藏
      previewVisible: false
    }
  },
  created() {
    // 调用商品分类请求
    this.getGoodsApi()
  },
  methods: {
    // 封装商品分类列表请求
    getGoodsApi() {
      getGoodsApi().then((res) => {
        this.goodsList = res.data.data
      })
    },
    // 封装参数列表请求
    getParamsListApi(val) {
      getParamsListApi({
        id: this.addGoodsForm.goods_cat[2],
        sel: val
      }).then((res) => {
        // 判断是否many
        if (val === 'many') {
          // 字符转换数组
          res.data.data.forEach((item) => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          })
          this.manyList = res.data.data
          return
        }
        this.onlyList = res.data.data
      })
    },
    // 封装添加商品请求
    getAddApi(val) {
      getAddApi(val).then(res => {
        if (res.data.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        }
        this.$message.success('添加商品成功')
        // 跳转到商品列表页
        this.$router.push('goods')
      })
    },
    // tab 被选中时触发
    tabsClick(tabs) {
      if (tabs.name === '1') {
        this.getParamsListApi('many')
      }
      if (tabs.name === '2') {
        this.getParamsListApi('only')
      }
      // 解决没有点击动态参数与静态参数的tab页，直接前往最后一页添加商品时没有动态参数与静态属性
      if (tabs.name === '4') {
        if (this.manyList.length === 0) {
          this.getParamsListApi('many')
        }
        if (this.onlyList.length === 0) {
          this.getParamsListApi('only')
        }
      }
    },
    // 商品分类选中项变化触发
    classifyChange() {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return
      }
      this.addGoods.goods_cat = []
    },
    // 点击商品参数tab触发效验
    beforeLeave(activeName, oldActiveName) {
      if (
        oldActiveName === '0' &&
        this.addGoodsForm.goods_cat.length !== 3 &&
        !this.addGoodsForm.goods_name
      ) {
        this.$message.error('请完善基本信息')
        return false
      }
    },
    // 点击已上传的图片时，触发预览
    handlePreview(file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 移除图片时，触发
    handleRemove(file, fileList) {
      // 路径
      const fliePath = file.response.data.tmp_path

      const i = this.addGoodsForm.pics.findIndex((x) => {
        return x.pic === fliePath
      })
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 图片上传成功，触发
    handleSucess(response) {
      console.log(response)
      // 拼接地址对象
      const picePath = { pic: response.data.tmp_path }
      // 赋值
      this.addGoodsForm.pics.push(picePath)
    },
    // 点击添加商品按钮
    addFormBtn() {
      this.$refs.addGoodsFormRef.validate((valid) => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项')
        }
        // 表单通过效验
        const formList = _.cloneDeep(this.addGoodsForm)
        // 以为','分割的分类列表id
        formList.goods_cat = formList.goods_cat.join(',')
        // 处理动态参数
        this.manyList.forEach((item) => {
          const manyInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addGoodsForm.attrs.push(manyInfo)
        })
        // 处理静态属性
        this.onlyList.forEach((item) => {
          const onlyInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addGoodsForm.attrs.push(onlyInfo)
        })

        // 处理富文本内容带有标签
        this.addGoodsForm.goods_introduce = this.addGoodsForm.goods_introduce.replace('<p>', '')
        this.addGoodsForm.goods_introduce = this.addGoodsForm.goods_introduce.replace('</p>', '')
        // 深拷贝赋值与富文本内容赋值
        formList.attrs = this.addGoodsForm.attrs
        formList.goods_introduce = this.addGoodsForm.goods_introduce

        // 调用添加商品请求
        this.getAddApi(formList)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}

.el-alert {
  margin-bottom: 15px;
}

.el-checkbox {
  margin: 0 7px 0 0 !important;
}

.preview-img {
  width: 100%;
}

/deep/.ql-editor {
  height: 300px;
}

.addBtn {
  margin-top: 15px;
}
</style>
